import type { IWorld } from '$lib/ecs';
import type { Entity } from './components';
import { AStarFinder } from 'astar-typescript';
import { getGrid } from './pos3';
import { gridMapOn } from './pos2';

export type CanPass = (world: IWorld, es: Entity[]) => boolean;

export const findStepPath2D = (world: IWorld, canPass: CanPass, r: number, z: number, x: number, y: number, x1: number, y1: number) => {
  const [sx0, sx1] = [x, x1].sort();
  const [sy0, sy1] = [y, y1].sort();
  // console.log('from', x, y, 'to', x1, y1);
  const grid = getGrid(world, z, sx0-r, sy0-r, sx1+r, sy1+r);
  const bitMap = gridMapOn(grid, sx0-r, sy0-r, sx1+r, sy1+r, (tile) => canPass(world, tile.stack) ? 0 : 1);
  // console.log(bitMap);
  bitMap.get(y).set(x, 0); // make sure initial point is walkable
  // console.log(sy0-r, sx0-r, sy1-sy0+r*2+1, sx1-sx0+r*2+1);
  // console.log('OH HOH');
  const matrix = Array.from({ length: sy1-sy0+r*2+1 }, (_, yy) => Array.from({ length: sx1-sx0+r*2+1 }, (_, xx) => bitMap.get(yy+sy0-r).get(xx+sx0-r)));
  // console.log('canPass', matrix);
  const pf = new AStarFinder({
    grid: {
      matrix,
    },
    diagonalAllowed: true,
  });
  const path = pf.findPath({x: x-sx0+r, y: y-sy0+r}, {x: x1-sx0+r, y: y1-sy0+r});
  // console.log('PATH', path);
  if (path.length > 1) {
    const [rx0, ry0] = path[0]
    const [rx, ry] = path[1];
    return [rx-rx0, ry-ry0];
  } else if (path.length > 0) {
    return true;
  } else {
    return false;
  }
};
